package com.example.smartpark.controller;

import com.example.smartpark.common.Result;
import com.example.smartpark.dto.UserLoginDTO;
import com.example.smartpark.dto.UserRegisterDTO;
import com.example.smartpark.service.UserService;
import com.example.smartpark.vo.LoginVO;
import com.example.smartpark.vo.UserVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * 认证控制器
 * 处理用户登录、注册等认证相关请求
 */
@Slf4j
@RestController
@RequestMapping("/api/auth")
public class AuthController {

    @Autowired
    private UserService userService;

    /**
     * 用户注册
     *
     * @param registerDTO 注册信息
     * @return 注册结果
     */
    @PostMapping("/register")
    public Result<UserVO> register(@RequestBody @Validated UserRegisterDTO registerDTO) {
        log.info("收到用户注册请求: {}", registerDTO.getUsername());
        UserVO userVO = userService.register(registerDTO);
        return Result.success(userVO, "注册成功");
    }

    /**
     * 用户登录
     *
     * @param loginDTO 登录信息
     * @return 登录结果（包含token和用户信息）
     */
    @PostMapping("/login")
    public Result<LoginVO> login(@RequestBody @Validated UserLoginDTO loginDTO) {
        log.info("收到用户登录请求: {}", loginDTO.getUsername());
        try {
            LoginVO loginVO = userService.login(loginDTO);
            return Result.success(loginVO, "登录成功");
        } catch (Exception e) {
            log.error("登录失败: {}", e.getMessage(), e);
            return Result.error("登录失败: " + e.getMessage());
        }
    }

    /**
     * 检查用户名是否已存在
     *
     * @param username 用户名
     * @return 检查结果
     */
    @GetMapping("/check-username")
    public Result<Boolean> checkUsername(@RequestParam String username) {
        log.info("检查用户名是否存在: {}", username);
        boolean exists = userService.checkUsernameExists(username);
        return Result.success(exists);
    }
} 